/*
 * @# ImageHandler.java 2011-12-29 下午06:57:44
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.album.io;

import java.io.File;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.ianswer.common.io.image.preview.PreviewManager;
import com.ianswer.px.utils.AppPropReader;
import com.ianswer.px.utils.UserFileUtils;

/**
 * @author alvin hwang
 */
public final class AblumPhotoHandler {

	private AblumPhotoHandler() {
		// empty!
	}

	public static String handle(Long userId, MultipartFile image) throws IOException {
		if (image == null) {
			return StringUtils.EMPTY;
		}

		String savePath = AppPropReader.getPhotoSavePath();
		String filePath = UserFileUtils.file(userId, image.getOriginalFilename());
		String source = savePath + filePath;

		makeDirectoryIfNonexists(source);
		image.transferTo(new File(source));

		PreviewManager previewManager = PreviewManager.magickPreviewManager();

		previewManager.height(source, AlbumPhotoSize.H80.path(source), AlbumPhotoSize.H80.HEIGHT);
		previewManager.height(source, AlbumPhotoSize.H160.path(source), AlbumPhotoSize.H160.HEIGHT);
		previewManager.height(source, AlbumPhotoSize.H220.path(source), AlbumPhotoSize.H220.HEIGHT);
		previewManager.height(source, AlbumPhotoSize.H400.path(source), AlbumPhotoSize.H400.HEIGHT);
		previewManager.height(source, AlbumPhotoSize.H600.path(source), AlbumPhotoSize.H600.HEIGHT);
		previewManager.width(source, AlbumPhotoSize.W900.path(source), AlbumPhotoSize.W900.WIDTH);

		return filePath;
	}

	private static void makeDirectoryIfNonexists(String source) {
		File dir = new File(source).getParentFile();
		if (!dir.exists()) {
			dir.mkdirs();
		}
	}

}
